#include "Iot_Comm_Data.h"
#include "timer.h"
#include "usart.h"
#include "gpio.h"
#include "Rs485Data.h"
#include <string.h>
#include "DataBase.h"

#define  IOT_BUFF_MAX  1024
#define  VOLT_UNIT  1000
#define  CURR_UNIT  1000
#define  CELL_UNIT  1000
#define  TEMP_UNIT  10
#define  SOC_UNIT  	10


void Iot_Init(void)
{
		DC12V_En_Set_Gpio(ON);
}

u8 Iot_Comm_Data(void)
{
		static u8 send_delay = 40;
		u16 size = 0;
	  u16 iot_buff_size = 0;
		u8 iot_buff_msg[IOT_BUFF_MAX] = {0};

		if(gTime1s_FlagC!=ON)
		{
				return gRET_NG;
		}
		
		if(send_delay > 0)
		{
				send_delay--;
				return gRET_NG;
		}
		
		size = sprintf((char *)&iot_buff_msg[iot_buff_size], "&volt_line,%d.%03d", (gVOLT_LINE/VOLT_UNIT), (gVOLT_LINE%VOLT_UNIT));
		iot_buff_size += size;
		size = sprintf((char *)&iot_buff_msg[iot_buff_size], "&curr_line,%d.%03d", (gCURR_LINE/CURR_UNIT), (gCURR_LINE%CURR_UNIT));
		iot_buff_size += size;
		size = sprintf((char *)&iot_buff_msg[iot_buff_size], "&cell1,%d.%03d", (gCELL_VOLT(0)/CELL_UNIT), (gCELL_VOLT(0)%CELL_UNIT));
		iot_buff_size += size;
		size = sprintf((char *)&iot_buff_msg[iot_buff_size], "&cell2,%d.%03d", (gCELL_VOLT(1)/CELL_UNIT), (gCELL_VOLT(1)%CELL_UNIT));
		iot_buff_size += size;
		size = sprintf((char *)&iot_buff_msg[iot_buff_size], "&cell3,%d.%03d", (gCELL_VOLT(2)/CELL_UNIT), (gCELL_VOLT(2)%CELL_UNIT));
		iot_buff_size += size;
		size = sprintf((char *)&iot_buff_msg[iot_buff_size], "&cell4,%d.%03d", (gCELL_VOLT(3)/CELL_UNIT), (gCELL_VOLT(3)%CELL_UNIT));
		iot_buff_size += size;
		size = sprintf((char *)&iot_buff_msg[iot_buff_size], "&cell5,%d.%03d", (gCELL_VOLT(4)/CELL_UNIT), (gCELL_VOLT(4)%CELL_UNIT));
		iot_buff_size += size;
		size = sprintf((char *)&iot_buff_msg[iot_buff_size], "&cell_max,%d.%03d", (gCELL_VOLT_MAX/CELL_UNIT), (gCELL_VOLT_MAX%CELL_UNIT));
		iot_buff_size += size;
		size = sprintf((char *)&iot_buff_msg[iot_buff_size], "&cell_min,%d.%03d", (gCELL_VOLT_MIN/CELL_UNIT), (gCELL_VOLT_MIN%CELL_UNIT));
		iot_buff_size += size;
		size = sprintf((char *)&iot_buff_msg[iot_buff_size], "&temp_max,%d.%01d", (gTEMP_PACK_MAX/TEMP_UNIT), (gTEMP_PACK_MAX%TEMP_UNIT));
		iot_buff_size += size;
		size = sprintf((char *)&iot_buff_msg[iot_buff_size], "&temp_min,%d.%01d", (gTEMP_PACK_MIN/TEMP_UNIT), (gTEMP_PACK_MIN%TEMP_UNIT));
		iot_buff_size += size;
		size = sprintf((char *)&iot_buff_msg[iot_buff_size], "&sys_soc,%d.%01d", (gSYS_SOC/SOC_UNIT), (gSYS_SOC%SOC_UNIT));
		iot_buff_size += size;	
		
		Uart3_Send_Pack(RS485S2_BMS_ID,RS485_FUN_COMM1,iot_buff_size,iot_buff_msg);

		return gRET_OK;
}

